__author__ = 'haind'
from redis.exceptions import ResponseError
from db_wrapper import db_conn
import db_cloud
import time
from threading import Thread

db_pool = db_cloud.NotiCloud()
r = db_conn.MyRedis()


def popall(name):
    res = None
    while True:
        try:
            v_conn = r.conn
            pipe = v_conn.pipeline()
            pipe.multi()
            pipe.zrange(name, 0, -1)
            pipe.delete(name)
            v_res = pipe.execute()
            if v_res:
                res = v_res[0]
            break
        except ResponseError:
            time.sleep(1)
    return res


def work():
    while True:
        v_queued_logs = popall('pushed_log')
        if v_queued_logs:
            for v_log in v_queued_logs:
                if v_log:
                    v_log = eval(v_log)
                    print v_log
                    if len(v_log) == 5:
                        db_pool.log(v_log[0], v_log[1], v_log[2], v_log[3], v_log[4])
        else:
            time.sleep(5)

Thread(target=work).start()